package com.jeesuite.bestpl.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeesuite.bestpl.api.IPostService;
import com.jeesuite.bestpl.dao.entity.CommentEntity;
import com.jeesuite.bestpl.dao.entity.PostCategoryEntity;
import com.jeesuite.bestpl.dao.entity.PostEntity;
import com.jeesuite.bestpl.dao.entity.TagEntity;
import com.jeesuite.bestpl.dao.mapper.CommentEntityMapper;
import com.jeesuite.bestpl.dao.mapper.PostCategoryEntityMapper;
import com.jeesuite.bestpl.dao.mapper.PostEntityMapper;
import com.jeesuite.bestpl.dao.mapper.TagEntityMapper;
import com.jeesuite.bestpl.dto.Comment;
import com.jeesuite.bestpl.dto.IdNamePair;
import com.jeesuite.bestpl.dto.Page;
import com.jeesuite.bestpl.dto.PageQueryParam;
import com.jeesuite.bestpl.dto.Post;
import com.jeesuite.bestpl.exception.DemoBaseException;
import com.jeesuite.bestpl.task.PostStatStoreageTask;
import com.jeesuite.common.util.BeanCopyUtils;
import com.jeesuite.mybatis.plugin.pagination.PageExecutor;
import com.jeesuite.mybatis.plugin.pagination.PageExecutor.PageDataLoader;
import com.jeesuite.mybatis.plugin.pagination.PageParams;

@Service
public class PostService implements IPostService{

	private @Autowired PostCategoryEntityMapper postCategoryMapper;
	private @Autowired PostEntityMapper postmapper;
	private @Autowired CommentEntityMapper commentMapper;
	private @Autowired TagEntityMapper tagMapper;
	
	@Override
	@Transactional
	public void addPosts(Post post) {
		
		PostEntity entity = BeanCopyUtils.copy(post, PostEntity.class);
		
		if(entity.getCategoryId() == null || entity.getCategoryId() == 0){
			throw new DemoBaseException("请选择栏目");
		}
		
		PostCategoryEntity categoryEntity = postCategoryMapper.selectByPrimaryKey(entity.getCategoryId());
		if(categoryEntity == null)throw new DemoBaseException("栏目不存在");
		
		int[] tagIds = null;
		if(StringUtils.isNotBlank(entity.getTags())){
			entity.setTags(entity.getTags().replaceAll(";|，|\\s+", ","));
			String[] tags = entity.getTags().split(",");
			TagEntity tagEntity;
			
			tagIds = new int[tags.length];
			for (int i = 0; i < tagIds.length; i++) {
				tagEntity = tagMapper.findByName(tags[i]);
				if(tagEntity == null){
					tagEntity = new TagEntity();
					tagEntity.setName(tags[i]);
					tagEntity.setReferCount(1);
					tagEntity.setTagType(1);
					tagMapper.insertSelective(tagEntity);
				}else{
					tagEntity.setReferCount(tagEntity.getReferCount() + 1);
					tagMapper.updateByPrimaryKeySelective(tagEntity);
				}
				tagIds[i] = tagEntity.getId();
			}
		}
		
		entity.setCreatedAt(new Date());
		postmapper.insertSelective(entity);
		//
		//插入关联关系
		if(tagIds != null)tagMapper.addTagRalate(entity.getId(), tagIds);
	}
	
	
	@Override
	public Post findPostById(int id) {
		PostEntity entity = postmapper.selectByPrimaryKey(id);
		if(entity == null)throw new DemoBaseException("数据不存在或已删除");
		
		//浏览数简单处理，按查询统计
		PostStatStoreageTask.addStatData(id, 1);
		return buildPost(entity);
	}
	
	
	@Override
	public List<Post> findTopPost(int categoryId,String sortType, int top) {
		List<Post> result = new ArrayList<>();
		List<PostEntity> posts = postmapper.findTopPosts(categoryId, sortType, top);
		for (PostEntity entity : posts) {
			result.add(buildPost(entity));
		}
		return result;
	}
	
	
	@Override
	public Page<Post> pageQueryPost(PageQueryParam param) {
		PageParams pageParam = new PageParams(param.getPageNo(), param.getPageSize());
		com.jeesuite.mybatis.plugin.pagination.Page<PostEntity> page = postmapper.findByConditons(pageParam, param.getConditions(), param.getOrderBy());
		
		List<Post> datas = new ArrayList<>();
		
		for (PostEntity entity : page.getData()) {
			datas.add(buildPost(entity));
		}
		
		return new Page<>(param.getPageNo(), param.getPageSize(), page.getTotal(), datas);
	}
	@Override
	public void addPostComment(Comment comment) {
		PostEntity entity = postmapper.selectByPrimaryKey(comment.getPostId());
		if(entity == null)throw new DemoBaseException("数据不存在或已删除");
		
		CommentEntity commentEntity = BeanCopyUtils.copy(comment, CommentEntity.class);
		commentEntity.setCreatedAt(new Date());
		
		commentMapper.insertSelective(commentEntity);
		//评论数统计
		PostStatStoreageTask.addStatData(comment.getPostId(), 2);
	}
	
	@Override
	public Page<Comment> pageQueryPostComment(int postId,int pageNo,int pageSize) {
		
		com.jeesuite.mybatis.plugin.pagination.Page<CommentEntity> page = PageExecutor.pagination(new PageParams(pageNo, pageSize), new PageDataLoader<CommentEntity>() {
			@Override
			public List<CommentEntity> load() {
				return commentMapper.findByPost(postId);
			}
		});
        List<Comment> datas = BeanCopyUtils.copy(page.getData(), Comment.class);
		return new Page<>(pageNo, pageSize, page.getTotal(), datas);
	}
	@Override
	public List<IdNamePair> findAllPostCategory() {
		List<IdNamePair> result = new ArrayList<>();
		List<PostCategoryEntity> list = postCategoryMapper.selectAll();
		for (PostCategoryEntity entity : list) {
			result.add(new IdNamePair(entity.getId(), entity.getName()));
		}
		return result;
	}


	@Override
	public List<String> findHotTags(int limit) {
		List<String> result = new ArrayList<>();
		List<TagEntity> entitys = tagMapper.findHotTags(limit);
		for (TagEntity tagEntity : entitys) {
			result.add(tagEntity.getName());
		}
		return result;
	}

	
	private Post buildPost(PostEntity entity){
		Post post = BeanCopyUtils.copy(entity, Post.class);
		post.setCategory(postCategoryMapper.selectByPrimaryKey(entity.getCategoryId()).getName());
		return post;
	}
	
	
}
